import 'dart:io';
import 'dart:ui';

import 'package:fate_blind_box/widget/appbar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:fluwx/fluwx.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../theme/theme_color.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';

class Invite4Ui extends StatelessWidget {
  const Invite4Ui({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _Invite4Widget();
  }
}

class _Invite4Widget extends StatefulWidget {
  const _Invite4Widget({Key? key}) : super(key: key);

  @override
  State<_Invite4Widget> createState() => _Invite4WidgetState();
}

class _Invite4WidgetState extends State<_Invite4Widget> {
  String _inviteCode = "";
  String _profileNo = "";
  List<GlobalKey> rootKeyList = [
    GlobalKey(),
    GlobalKey(),
  ];

  int currentRootKey = 0;

  // Tencent.instance.registerApp(appId: "1106303270", universalLink: 'https://ahpsvr.anyeoa.com');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getQr();
    // _initFluwx();
  }

  // _initFluwx() async {
  //   await registerWxApi(
  //       appId: "wx20bdf249241ce720",
  //       doOnAndroid: true,
  //       doOnIOS: true,
  //       universalLink: "https://ahpsvr.anyeoa.com");
  //   var result = await isWeChatInstalled;
  //   print("is installed $result");
  // }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: HzAppBar(
        text: '邀请好友',
        backgroundColor: ThemeColor.color19CF8F23,
      ),
      body: Container(
        color: ThemeColor.color19CF8F23,
        child: SingleChildScrollView(
          child: Column(
            children: [
              GestureDetector(
                  onLongPress: () {
                    _capturePng();
                  },
                  child: buildBanner(size)),
              _bottomItem(size),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildBanner(final size) {
    List<String> imgList = [
      "images/Invite_image_1.png",
      "images/Invite_image_2.png",
    ];

    return Container(
      padding: EdgeInsets.fromLTRB(15.w, 5.w, 15.w, 0),
      // color: const Color.fromRGBO(113, 89, 245, 0.14),
      // padding: EdgeInsets.symmetric(horizontal: 20),
      // height: 560,
      // width: size.width *0.9,
      child: AspectRatio(
        //设置图片的展示比例之后，可以不设置外层的宽度，或者设置成infinity630 / 924
        aspectRatio: 320 / 512,
        child: Swiper(
          itemCount: imgList.length,
          itemBuilder: (BuildContext context, int index) {
            currentRootKey = index;
            return RepaintBoundary(
              key: rootKeyList[index],
              child: Stack(
                children: [
                  Center(
                    child: Container(
                        // padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                        color: Colors.white,
                        // padding: const EdgeInsets.symmetric(vertical: 5, ),
                        child: ClipRRect(
                          // borderRadius: BorderRadius.circular(5),
                          child: Image.asset(
                            imgList[index],
                            fit: BoxFit.fill,
                          ),
                        )),
                  ),
                  Center(
                    child: Container(
                      width: 150.w,
                      height: 154.w,
                      margin: EdgeInsets.only(
                        top: 192.w,
                      ),
                      color: Colors.white,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            height: 10,
                          ),
                          Text(
                            '都肆商圈ID：' + _profileNo,
                            style: const TextStyle(
                                fontSize: 11, color: Color(0xFF401C66)),
                          ),
                          // const SizedBox(height: 5,),
                          QrImageView(
                            padding: const EdgeInsets.all(3),
                            backgroundColor: Colors.white,
                            data: _getQrInfo(),
                            version: QrVersions.auto,
                            size: 114.w,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
          //分页指示器
          pagination: _buildSwiperPagination(),
          //页面上的左右箭头
          control: SwiperControl(
              color: ThemeColor.colorCF8F23,
              size: 20.w,
              padding: EdgeInsets.zero),
          //自动轮播
          autoplay: false,
          loop: true,
        ),
      ),
    );
  }

  /// 分页指示器
  _buildSwiperPagination() {
    return SwiperPagination(
      alignment: Alignment.bottomCenter,
      builder: SwiperCustomPagination(
        builder: (BuildContext context, SwiperPluginConfig config) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(config.itemCount, (index) {
              bool isActive = index == config.activeIndex;
              return Container(
                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                decoration: BoxDecoration(
                  color: isActive ? ThemeColor.colorCF8F23 : Colors.grey[300],
                  borderRadius: BorderRadius.circular(isActive ? 16.0 : 8.0),
                ),
                width: isActive ? 16.0 : 8.0,
                height: 8.0,
              );
            }),
          );
        },
      ),
    );
  }

  Widget _bottomItem(final size) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // _buildWechatBtn(),
        Container(
            // color: Colors.red,
            // color: const Color.fromRGBO(113, 89, 245, 0.14),
            margin: const EdgeInsets.fromLTRB(0, 70, 0, 0),
            width: MediaQuery.of(context).size.width,
            height: 130,
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.start,
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.center,
                  margin: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  height: 45,
                  width: size.width - 80,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(22.5)),
                    gradient: LinearGradient(colors: [
                      ThemeColor.colorCF8F23,
                      ThemeColor.colorD88E4B,
                    ]),
                  ),
                  child: const Text(
                    '长按图片下载图片',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
              ],
            )),
      ],
    );
  }

  Widget _buildIconText(String icon, String text) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(icon, width: 45, height: 70),
      ],
    );
  }

  /// 微信按钮
  Widget _buildWechatBtn() {
    return Container(
      color: const Color.fromRGBO(113, 89, 245, 0.14),
      margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
      //
      child: Container(
        margin: const EdgeInsets.fromLTRB(60, 20, 60, 0),
        padding: const EdgeInsets.symmetric(vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(child: Container()),
            InkWell(
              onTap: () {
                _onClick('wechat', _getQrInfo());
              },
              child: _buildIconText("images/ic_wechatfriend.png", ""),
            ),
            const SizedBox(
              width: 60,
            ),
            InkWell(
              onTap: () {
                _onClick('circle', _getQrInfo());
              },
              child: _buildIconText("images/ic_friendCicle.png", ""),
            ),
            Expanded(child: Container()),
          ],
        ),
      ),
    );
  }

  String _getQrInfo() {
    debugPrint('xxxx   ${HttpConfig.baseUrl}?invite_code=$_inviteCode');
    return _inviteCode.isEmpty
        ? ""
        : HttpConfig.baseUrl + "?invite_code=$_inviteCode";
  }

  _getQr() {
    loading(() async {
      final res = await Api.getInstance().getMemberInfo(Provider.memberId);
      if (res?['data']?['shareCode']?.toString().isNotEmpty == true) {
        setState(() {
          Provider.nickName = res['data']['nickName'];
          _inviteCode = res['data']['shareCode'];
          _profileNo = res['data']['profileNo'];
          debugPrint(_inviteCode);
        });
      } else {
        toast("获取邀请码失败！");
      }
    });
  }

  Future<Uint8List?> _capturePng() async {
    try {
      if (!kIsWeb && (Platform.isAndroid || Platform.isIOS)) {
        // PermissionStatus storageStatus = await Permission.storage.status;
        // if (storageStatus != PermissionStatus.granted) {
        //   storageStatus = await Permission.storage.request();
        // //   print('ccc $storageStatus');
        //   if (storageStatus != PermissionStatus.granted) {
        //     toast("请先授权");
        //     return null;
        //   }
        // }

        // Permission permission = Permission.storage;
        // PermissionStatus status = await permission.status;
        // // PermissionStatus storageStatus = await Permission.storage.status;
        // if (status.isGranted) {
        //   //权限通过
        // } else if (status.isDenied) {
        //   //权限拒绝， 需要区分IOS和Android，二者不一样
        //   requestPermission(permission);
        // } else if (status.isPermanentlyDenied) {
        //   //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
        //   openAppSettings();
        // } else if (status.isRestricted) {
        //   //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
        //   openAppSettings();
        // } else {
        //   //第一次申请
        //   requestPermission(permission);
        // }
      }

      // RenderRepaintBoundary boundary = _rootKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      // RenderRepaintBoundary boundary = rootKeyList[currentRootKey].currentContext as RenderRepaintBoundary;
      RenderRepaintBoundary boundary = rootKeyList[currentRootKey]
          .currentContext!
          .findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List? pngBytes = byteData?.buffer.asUint8List();
      if (pngBytes != null) {
        final res = await ImageGallerySaver.saveImage(pngBytes);
        if (res == null || res == '') {
          toast("保存失败");
        } else {
          toast("保存到相册成功");
        }
      }
      return pngBytes; //这个对象就是图片数据
    } catch (e) {
      print('=============');
      print(e);
    }
    return null;
  }
}

void requestPermission(Permission permission) async {
  //发起权限申请
  PermissionStatus status = await permission.request();
  // 返回权限申请的状态 status
  print('权限状态$status');
  if (status.isPermanentlyDenied) {
    openAppSettings();
  }
}

_onClick(String id, String Qr) {
  switch (id) {
    case 'wechat':
      //个人设置
      String asset = 'images/ic_inviteLogo.png';

      String asset1 = Provider.nickName;
      print('==========');
      print(asset1);
      var model = WeChatShareWebPageModel(
        Qr,
        title: '偶然遇见另一半',
        scene: WeChatScene.SESSION,
        description: '<$asset1>\n邀请您参加偶然遇见、寻找您心仪的另一半，开启您的幸福之旅！',
        thumbnail: WeChatImage.asset(asset, suffix: 'png'),
      );

      shareToWeChat(model);
      break;
    case 'circle':
      String asset = 'images/ic_inviteLogo.png';
      var fluwx;
      String linkUrl =
          "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83erg9HmcT5ld2GYIBaqCK2KB25dUSSqYFRgjjqkJWDZAn8f0In7nVQ0dylVWlPA8aBh8XYUL0RzTZQ/132";
      var model = WeChatShareWebPageModel(
        Qr,
        title: '偶然遇见另一半',
        scene: WeChatScene.TIMELINE,
        description: '<${Provider.nickName}>\n邀请您参加偶然遇见、寻找您心仪的另一半，开启您的幸福之旅！',
        mediaTagName: 'dd',
        thumbnail: WeChatImage.asset(asset, suffix: 'png'),
      );

      shareToWeChat(model);
      break;
    case 'QQ':
      // TencentKitPlatform.instance.shareText(
      //   scene: TencentScene.kScene_QQ,
      //   summary: '分享测试',
      // );

      break;
    case 'qzone':
      // TencentKitPlatform.instance.shareText(
      //   scene: TencentScene.kScene_QZone,
      //   summary: '分享测试',
      // );
      break;

      defalut:
      break;
  }
}
